<?php
// +----------------------------------------------------------------------
// | HisiPHP框架[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2021 http://www.hisiphp.com
// +----------------------------------------------------------------------
// | HisiPHP承诺基础框架永久免费开源，您可用于学习和商用，但必须保留软件版权信息。
// +----------------------------------------------------------------------
// | Author: 橘子俊 <364666827@qq.com>，开发者QQ群：50304283
// +----------------------------------------------------------------------

namespace app\system\admin;

use Env;
use hisi\Dir;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\OrderUser as OrderUserService;
use app\system\model\SystemRole as RoleModel;
use think\Db;
/**
 * 后台默认首页控制器
 * @package app\system\admin
 */

class Index extends Admin
{
    /**
     * 首页
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function index()
    {
    	if ($this->request->isPost()) {
    		return $this->_getIndexOrders();
    	}

    	$assign = [];
    	// 获取快捷菜单ID

    	if (!cache('?'.QUICK_MENU . ADMIN_ID)) {
    		$menuList = db('system_menu')->where('uid', '=', ADMIN_ID)->column('id,ori_id');
    		$quickMenuIds = array_merge(array_keys($menuList), array_values($menuList));
    		cache(QUICK_MENU . ADMIN_ID, $quickMenuIds, 864000);
    	} else {
    		$quickMenuIds = cache(QUICK_MENU . ADMIN_ID);
    	}
    	$assign['quick_menu_ids'] = $quickMenuIds;

    	if (cookie('?hisi_iframe')) {
    		$hisiIframe = cookie('hisi_iframe');
    	} else {
    		$hisiIframe = db('system_user')->where('id', '=', ADMIN_ID)->value('iframe');
    		cookie('hisi_iframe', $hisiIframe);
    	}

    	if ($hisiIframe) {
            $this->view->engine->layout(false);
            return $this->assign($assign)->fetch('iframe');
        } else {
        	$assign['orderFrom'] = config('mimo.order_from');
        	return $this->assign($assign)->fetch();
        }
    }

    /**
     * 欢迎首页
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function welcome()
    {
    	if ($this->request->isPost()) {
    		return $this->_getIndexOrders();
    	}

    	$assign['orderFrom'] = config('mimo.order_from');
    	return $this->assign($assign)->fetch('index');
    }

    /**
     * 获取首页订单
     *
     * @author KING
     * @date 2020年6月26日
     *
     */
    private function _getIndexOrders() {
    	$result = ['list' => []];
    	$where = [];
    	$where[] = ['status', 'in', [0, 1]];
        $where[] = ['client_status', '<>', 99];
    	$where[] = ['tail_status', '=', 0];

        //订单加一级
        order_level($where,'');
    	$list = db('order')->where($where)->orderRaw('field(stock_type, 9) desc,shipment_time asc')->select();

    	$orderSizeService = new OrderSizeService();
		$orderUserService = new OrderUserService();
    	$skus = array_column($list, 'sku');
    	$skuMap = db('sku')->where('sku', 'in', $skus)->column('pic,ori_pic,cost,chewei_price,sixian_price,zhuanji_price,is_public', 'sku');
    	$factoryOutgoKV = getFactoryOutgoKV(null);

    	$clientStatusMap = config('mimo.client_status');
    	$skuWhere=[['sku', 'in', $skus],['available_count','>',0]];
        $skuStockList=db('sku_stock')->where($skuWhere)->field('sku,size_name,sum(available_count) as available_count,sum(defective_count) as defective_count,factory_id')->group("sku,factory_id,size_name")->select();
        $stockSkuKeyList=[];//工厂与sku规类成衣库存
        foreach ($skuStockList as $stindex=>$stockinfo){
            if(!isset($stockSkuKeyList[$stockinfo['sku'].'_'.$stockinfo['factory_id']])){
                $stockSkuKeyList[$stockinfo['sku'].'_'.$stockinfo['factory_id']]='库存：';
            }
            $stockSkuKeyList[$stockinfo['sku'].'_'.$stockinfo['factory_id']].="[".$stockinfo['size_name'].":".$stockinfo['available_count']."] ";
        }
    	foreach ($list as $v) {
    		$skuInfo = arrayGet($skuMap, $v['sku'], []);

    		$key = 'caigou';
    		if ($v['caigou_status'] == 1 && $v['caichuang_status'] == 0) $key = 'caichuang';
    		elseif ($v['caichuang_status'] == 1 && $v['chejian_status'] == 0) $key = 'chejian';
    		elseif ($v['chejian_status'] == 1 && $v['tail_status'] == 0) $key = 'tail';

    		if ($key == 'tail') {
    			$v['quantity'] = $orderUserService->getShicaiCount($v['id']);	// 尾部取裁床数
				//$v['quantity'] = $orderSizeService->getShicaiCount($v['id']);	// 尾部取裁床数
    			$result[$key][] = [
    				'client_ordernum' => $v['client_ordernum'],
    				'sku' => $v['sku'],
                    'sku_stock'=>isset($stockSkuKeyList[$v['sku'].'_'.$v['factory_id']]) ? $stockSkuKeyList[$v['sku'].'_'.$v['factory_id']] : '',
    				'quantity' => $v['quantity'],
    				'shipment_time' => date("Y-m-d", $v['shipment_time']),
    				'factory_outgo_name' => arrayGet($factoryOutgoKV, $v['factory_outgo_id'], ''),
    				'pic' => arrayGet($skuInfo, 'ori_pic', ''),
    				'tags' => getOrderTag($v, $skuInfo),
    				'cost' => $v['quantity'] * arrayGet($skuInfo, 'cost', 0),
    				'chewei_price' => $v['quantity'] * arrayGet($skuInfo, 'chewei_price', 0),
    				'sixian_price' => $v['quantity'] * arrayGet($skuInfo, 'sixian_price', 0),
    				'zhuanji_price' => $v['quantity'] * arrayGet($skuInfo, 'zhuanji_price', 0),
    				'order_from' => $v['is_auto_import'],
    				'client_status' => arrayGet($clientStatusMap, $v['client_status'], 'unknown')
    			];
    			// 订单数
    			if (isset($result[$key.'_orders'])) {
    				$result[$key.'_orders']++;
    			} else {
    				$result[$key.'_orders']=1;
    			}


    		} else {
    			$v['quantity'] = $key=='chejian' ? ($orderSizeService->getShicaiCount($v['id'])) : $v['quantity']; // 车间时取裁床数
    			$result['list'][$v['factory_id']][$v['group_id']][$key][] = [
    				'client_ordernum' => $v['client_ordernum'],
    				'sku' => $v['sku'],
                    'sku_stock'=>isset($stockSkuKeyList[$v['sku'].'_'.$v['factory_id']]) ? $stockSkuKeyList[$v['sku'].'_'.$v['factory_id']] : '',
    				'quantity' => $v['quantity'],
    				'shipment_time' => date("Y-m-d", $v['shipment_time']),
    				'factory_outgo_name' => arrayGet($factoryOutgoKV, $v['factory_outgo_id'], ''),
    				'pic' => arrayGet($skuInfo, 'ori_pic', ''),
    				'tags' => getOrderTag($v, $skuInfo),
    				'cost' => $v['quantity'] * arrayGet($skuInfo, 'cost', 0),
    				'chewei_price' => $v['quantity'] * arrayGet($skuInfo, 'chewei_price', 0),
    				'sixian_price' => $v['quantity'] * arrayGet($skuInfo, 'sixian_price', 0),
    				'zhuanji_price' => $v['quantity'] * arrayGet($skuInfo, 'zhuanji_price', 0),
    				'order_from' => $v['is_auto_import'],
    				'client_status' => arrayGet($clientStatusMap, $v['client_status'], 'unknown')
    			];
    			// 订单数
    			if (isset($result['list'][$v['factory_id']][$v['group_id']][$key.'_orders'])) {
    				$result['list'][$v['factory_id']][$v['group_id']][$key.'_orders']++;
    			} else {
    				$result['list'][$v['factory_id']][$v['group_id']][$key.'_orders']=1;
    			}

    		}
    	}

    	$factoryKV = [];
    	$factoryKVTmp = [0 => '未分配'] + getFactoryKV();
    	$groupMap = [];
    	foreach ($factoryKVTmp as $k => $v) {
    		$fGroupKV = [0 => '未分组'] + getGroupKV($k);
    		$nGroupIdArr = array_keys(arrayGet($result['list'], $k, []));
    		$groupMap['f_'.$k] = $this->_filterGroup($fGroupKV, $nGroupIdArr);

    		$factoryKV['f_'.$k] = $v;
    	}
    	$result['factoryKV'] = $factoryKV;

    	$result['groupMap'] = $groupMap;
    	return $this->Json(1, '', $result);
    }

    /**
     * 过滤组别
     *
     * @author King
     * @date 2020年9月16日
     *
     * @param array $groupKV		组别键值对
     * @param array $groupIdArr		需保留组别ID
     * @return array
     */
    private function _filterGroup($groupKV, $groupIdArr) {
    	$result = [];
    	foreach ($groupKV as $k => $v) {
    		if (in_array($k, $groupIdArr)) $result['g_'.$k] = $v;
    	}
    	return $result;
    }


    /**
     * 清理缓存
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function clear()
    {
        $path   = env('runtime_path');
        $cache  = $this->request->param('cache/d', 0);
        $log    = $this->request->param('log/d', 0);
        $temp   = $this->request->param('temp/d', 0);

        if ($cache == 1) {
            Dir::delDir($path.'cache', true, false);

            $redis = getRedis();
            $redis->hDel(ORDER_ING, null);
            $redis->del($redis->keys(ORDER_HASH.'*'));
            $redis->del(KV_FACTORY);
            $redis->del(KV_FACTORY_OUTGO);
            $redis->del(KV_FACTORY_OUTGO_ALL);
            $redis->del($redis->keys(KV_DEPART.'*'));
            $redis->del($redis->keys(KV_GROUP.'*'));
            $redis->del(KV_STALLS);
            $redis->del(KV_STOREHOUSE);
            $redis->del($redis->keys(KV_STORESHELF.'*'));
            $redis->del(KV_UNIT);
            $redis->del(KV_USER);
            $redis->del(KV_USER_ALL);
            $redis->del(KV_SIZE);
            $redis->del(KV_PART);
            $redis->del(KV_REJECTS);
        }

        if ($temp == 1) {
        	Dir::delDir($path.'temp', true, false);
        }

        if ($log == 1) {
        	Dir::delDir($path.'log', true, false);
        }

        return $this->success('任务执行成功');
    }

	/**
     * 公告列表
     * @date 2021年3月8日
	 * @return array
     */
	public function notice(){
		if ($this->request->isAjax()) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$content    = $this->request->param('content/s');
    		$releaseTime    = $this->request->param('release_time/s','');
    		if ($content != '') {
    			$where[] = ['content', 'like', "%{$content}%"];
    		}
			if ($releaseTime != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $releaseTime));
    			$where[] = ['release_time', 'between', [$startTime, $endTime+86399]];
    		}

    		if (!IS_ROOT) {
	    		$roleIds = explode(',', ADMIN_ROLE);
	    		$whereTmp = "role_ids=''";
	    		foreach ($roleIds as $roleId) {
	    			$whereTmp .= " OR FIND_IN_SET({$roleId}, role_ids)";
	    		}
    		} else {
    			$whereTmp = "";
    		}

    		$data['data'] = db('notice')->where($where)->where($whereTmp)->page($page)->limit($limit)->order('create_time desc,release_time desc')->select();
    		$data['count'] = db('notice')->where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}
    	$assign = [];
    	return $this->assign($assign)->fetch();
	}

	/**
     * 公告显示
     * @date 2021年3月8日
	 * @return array
     */
	public function noticeShow(){
		if (!IS_ROOT) {
			$roleIds = explode(',', ADMIN_ROLE);
			$whereTmp = "role_ids=''";
			foreach ($roleIds as $roleId) {
				$whereTmp .= " OR FIND_IN_SET({$roleId}, role_ids)";
			}
		} else $whereTmp = "";

		$info = db('notice')->where('release_time !=0')->where($whereTmp)->field('id,title,content')->order('release_time desc')->findOrEmpty();
		$id = cache(NOTICE_READ.ADMIN_ID);
		if ($info && $id != $info['id']) {
			$info['content'] = htmlspecialchars_decode($info['content']);
		} else {
			$info = [];
			$data['content'] = '';
		}
		$data['data'] = $info;
		$data['code'] = $info?1:0;
		return json($data);
	}

	/**
     * 公告增加
     * @date 2021年3月8日
     */
	public function add(){
		if ($this->request->isPost()) {
    		$postData = $this->request->post();

    		if (isset($postData['role_ids']) && $postData['role_ids']) $postData['role_ids'] = implode(',', $postData['role_ids']);
    		$postData['create_time'] = $postData['update_time'] = time();
			$postData['admin_id'] = ADMIN_ID;
    		$id = db('notice')->insertGetId($postData);
    		if (!$id) {
    			return $this->error('保存失败');
    		}
    		return $this->success('保存成功', '');
    	}
		$assign = [
			'roles' => RoleModel::where('id', '>', IS_ROOT?0:1)->order('id asc')->column('id,name'),
		];
		$template = $this->request->param('template', 'form');
		return $this->assign($assign)->fetch($template);
	}

	/**
     * 公告编辑
     * @date 2021年3月8日
     */
	public function edit(){
		$id      = $this->request->param('id/d', 0);
		if ($this->request->isPost()) {
    		$postData = $this->request->post();
			$postData['update_time'] = time();
			if (isset($postData['role_ids']) && $postData['role_ids']) $postData['role_ids'] = implode(',', $postData['role_ids']);
    		$status = db('notice')->where('id',$id)->update($postData);
    		if (!$status) {
    			return $this->error('保存失败');
    		}
    		return $this->success('保存成功', '');
    	}
		$info=Db::name('notice')->where('id', $id)->find();
		$info['role_ids'] = $info['role_ids']!=''?explode(',', $info['role_ids']):[];
		$info['content'] = htmlspecialchars_decode($info['content']);
		$assign = [
			'id'=>$id,
			'formData'=>$info,
			'roles' => RoleModel::where('id', '>', IS_ROOT?0:1)->order('id asc')->column('id,name'),
		];
		$template = $this->request->param('template', 'form');
		return $this->assign($assign)->fetch($template);
	}

	/**
     * 公告删除
     * @date 2021年3月8日
     */
	public function del(){
		$id      = $this->request->param('id/d', 0);
        $release=Db::name('notice')->where('id', $id)->delete();
		if($release) return $this->Json(1);
		return $this->Json(0, '操作失败');
	}

	/**
     * 公告发布
     * @date 2021年3月8日
     */
	public function release()
    {
        $id      = $this->request->param('id/d', 0);
        $release=Db::name('notice')->where('id', $id)->update(['release_status'=>1,'release_time'=> time()]);
		if($release) return $this->Json(1);
		return $this->Json(0, '操作失败');
    }

    /**
     * 标记已读
     *
     * @author King
     * @date 2021年8月5日
     *
     */
	public function setTips(){
		$id = $this->request->param('id/d', 0);
		cache(NOTICE_READ.ADMIN_ID, $id, 30*86400);
		return $this->Json(1);
	}

	//列表查看公告
	public function view(){
        $id      = $this->request->param('id/d', 0);
        $notice=db('notice')->where('id', $id)->find();
        $notice['content'] =htmlspecialchars_decode($notice['content']);
        $assign['contentinfo']=$notice['content'];
        $systemUserKV = getSystemUserKV(true);
        @$notice['admin_user']=$systemUserKV[$notice['admin_id']];
        $assign['notice']=$notice;
        $template = $this->request->param('template', 'view');
        return $this->assign($assign)->fetch($template);
    }
}
